import type { FormInstance } from 'ant-design-vue';
import type { Ref } from 'vue';

interface FormHook {
  formRef: Ref<FormInstance | undefined>;
  submit(): void;
  reset(): void;
}

export interface IUseFormArg {
  form?: Ref<FormInstance | undefined> | undefined;
  validCallback?: () => void;
  id?: string
}
/**
 * 弹窗组件公共方法
 * @param options form 表单组件ElForm实例引用; validCallback 表单校验成功回调
 * @returns {
 *  formRef: 表单实例引用,
 *  submit(): 提交表单,
 *  reset(): 重置表单
 * }
 */
export default function useForm({
  form,
  validCallback = defaultValidCallback,
  id = 'id'
}: IUseFormArg): FormHook {
  const formRef = form || ref<FormInstance>();

  /**
   * 关闭弹窗时重置表单
   */
  function reset() {
    if (formRef.value?.model && formRef.value?.model[id]) {
      formRef.value.model[id] = undefined;
    }
    formRef.value?.resetFields();
  }

  /**
   * 表单校验
   */
  async function submit() {
    const valid = await formRef.value?.validate();
    if (valid) {
      validCallback()
    }
  }

  return {
    formRef,
    reset,
    submit
  };
}

function defaultValidCallback() {
  console.warn(
    `[传递validCallback表单检验成功回调覆盖此提示]: \nuseForm(formRef | undefined, validCallback)`
  );
}
